package com.dong.YOLOAPI;


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.BinaryMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.BinaryWebSocketHandler;

import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@Slf4j
public class imagesrecognize2 extends BinaryWebSocketHandler {
    // 存储所有连接的客户端会话
    private static final CopyOnWriteArraySet<WebSocketSession> sessions = new CopyOnWriteArraySet<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        sessions.add(session);
        log.info("session的内容是{}",session);
        System.out.println("YOLO识别新客户端连接，当前连接数: " + sessions.size());
    }
    @Override
    public void afterConnectionClosed(WebSocketSession session, org.springframework.web.socket.CloseStatus status) throws Exception {
        sessions.remove(session);
        System.out.println("客户端断开连接，当前连接数: " + sessions.size());
    }

    // 向所有客户端推送图像
    public static void broadcastFrame(byte[] frameData) {
        System.out.println("准备推送第二个区域识别到的图片，当前在线客户端数：" + sessions.size()); // 新增日志
        for (WebSocketSession session : sessions) {
            if (session.isOpen()) {
                try {
                    session.sendMessage(new BinaryMessage(frameData));
                    System.out.println("已向会话" + session.getId() + "推送数据，大小：" + frameData.length); // 新增
                } catch (IOException e) {
                    System.err.println("推送失败：" + e.getMessage());
                }
            } else {
                System.out.println("会话" + session.getId() + "已关闭，跳过推送");
            }
        }
    }
}
